#Copyright (c) 2025, Alibaba Cloud and its affiliates;
#Licensed under the Apache License, Version 2.0 (the "License");
#you may not use this file except in compliance with the License.
#You may obtain a copy of the License at

#   http://www.apache.org/licenses/LICENSE-2.0

#Unless required by applicable law or agreed to in writing, software
#distributed under the License is distributed on an "AS IS" BASIS,
#WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#See the License for the specific language governing permissions and
#limitations under the License.



import json

import fce_util.libs.localrun as localrun
import fce_util.deploys.resource_mgr as resource
import fce_util.libs.pods as pods
import fce_util.libs.constants as constants
from fce_util.libs import log as loggers
from fce_util.fceres import fce_res_common

logger = loggers.g_logger.logger

def deploy_resources(args):
    """
    FCE Ray cluster dependency resources deploy
    """
    logger.debug('deploy_resources enter,args:{}'.format(args))

    #kube_config = args.conf_path if args.conf_path else constants.KUBE_CONFIG_DEFAULT_PATH
    namespace = args.namespace if args.namespace else 'default'
    logger.info('deploy configMap start')
    resource.deploy_configMap(args.cluster_id, namespace)
    if not resource.checkServiceStatus(resource._getName(args.cluster_id, 'cm'), 'cm', namespace, 20, 1):
        stdout = f"deploy configMap: {resource._getName(args.cluster_id, 'cm')} failed"
        resource.clean('cm', resource._getName(args.cluster_id, 'cm'), namespace)
        logger.error(stdout)
        fce_res_common(success = False, errcode = 'RayCluster.ResourcesDeployFailed', errmsg = stdout)
        return
    logger.info('deploy configMap step1')
    '''
    #TBD
    logger.info('deploy storageclass start...')
    resource.deploy_SC(cluster_id, region_id, zone_id, vpc_id, vswitch_id)
    if not resource.checkServiceStatus(resource._getName(cluster_id, 'sc'), 'sc'):
        stdout = f"deploy storageclass: {resource._getName(cluster_id, 'sc')} failed"
        resource.clean('cm', resource._getName(cluster_id, 'cm'))
        resource.clean('sc', resource._getName(cluster_id, 'sc'))
        resource.clean('svc', resource._getName(cluster_id, 'svc'))
        logger.error(stdout)
        print(stdout)
        exit(-1)

     
    #depends on aliyun storage class
    logger.info('deploy storageclass start...')
    resource.deploy_SC(cluster_id, region_id, zone_id, vpc_id, vswitch_id)
    if not resource.checkServiceStatus(resource._getName(cluster_id, 'sc'), 'sc'):
        stdout = f"deploy storageclass: {resource._getName(cluster_id, 'sc')} failed"
        resource.clean('cm', resource._getName(cluster_id, 'cm'))
        resource.clean('sc', resource._getName(cluster_id, 'sc'))
        resource.clean('svc', resource._getName(cluster_id, 'svc'))
        logger.error(stdout)
        print(stdout)
        exit(-1)
     
    #TBD
    logger.info('deploy PVC start...')
    resource.deploy_PVC(cluster_id, resource._getName(cluster_id, 'sc'))
    if not resource.checkServiceStatus(resource._getName(cluster_id, 'pvc'), 'pvc'):
        stdout = f"deploy PVC: {resource._getName(cluster_id, 'pvc')} failed"
        resource.clean('pvc', resource._getName(cluster_id, 'pvc'))
        resource.clean('sc', resource._getName(cluster_id, 'sc'))
        resource.clean('cm', resource._getName(cluster_id, 'cm'))
        resource.clean('svc', resource._getName(cluster_id, 'svc'))
        logger.error(stdout)
        print(stdout)
        exit(-1)
    '''

    msg = {'Success': True}
    msg['Message'] = {
        'Msg': 'ConfigMap deploy success'
    }
    logger.info('deploy configMap step2, msg: {}'.format(msg))
    print(json.dumps(msg))

def FCE_deploy_resources(args):
    if args.deploy == 'res_obj':
        deploy_resources(args)
        return
    args.this_parser.print_help()

def make(parser):
    """
    FCE Ray Cluster List entry
    """
    parser.add_argument(
        '--cluster_id',
        dest='cluster_id',
        nargs='?',
        help='EHS obtain clusterId',
        )
    
    parser.add_argument( 
        '--namespace',
        dest='namespace',
        nargs = '?',
        metavar = ('NAMESPACE'),
        help='Ray Cluster Namespace',
        required=True,
        )
    
    parser.add_argument( 
        '--conf_path',
        dest='conf_path',
        nargs = '?',
        metavar = ('CONF_PATH'),
        help='Kube Config Path',
        required=True,
        )
    
    parser.set_defaults(
        func=FCE_deploy_resources,
        this_parser=parser
    )
